package leecode

func addTwoNumbersLCR(l1 *ListNode, l2 *ListNode) *ListNode {
	//反转链表
	l1 = reserveListLCR(l1)
	l2 = reserveListLCR(l2)
	result := addSumTwo(l1, l2)
	return reserveListLCR(result)
}

// 求和
func addSumTwo(l1 *ListNode, l2 *ListNode) *ListNode {
	dummyHead := &ListNode{}
	cur := dummyHead
	sum := 0 //和为0
	for l1 != nil || l2 != nil || sum != 0 {
		if l1 != nil {
			sum += l1.Val
		}
		if l2 != nil {
			sum += l2.Val
		}
		cur.Next = &ListNode{Val: sum % 10}
		sum = sum / 10
		cur = cur.Next
		if l1 != nil {
			l1 = l1.Next
		}
		if l2 != nil {
			l2 = l2.Next
		}
	}
	return dummyHead.Next
}

// 反转链表
func reserveListLCR(head *ListNode) (pre *ListNode) {
	cur := head
	for cur != nil {
		temp := cur.Next // temp  2 4
		cur.Next = pre   // nil 7
		pre = cur        // 7
		cur = temp       // 2
	}
	return
}
